package com.isslin.client.handler;

import com.alibaba.fastjson2.JSONObject;
import com.isslin.client.NettyClient;
import com.isslin.protocol.AjaxProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class ClientHandler extends SimpleChannelInboundHandler<Object> {

    Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object ajax) throws Exception {
        logger.info("接收到服务器信息");
        logger.info("{}", ajax);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接服务器成功");
        for (int i = 0; i < 10; i++) {
            AjaxProtocol protocol = new AjaxProtocol();
            protocol.setCode(200);
            protocol.setMsg("i = " + i);
            protocol.setData("package org.jeecg.modules.tool;import com.itextpdf.text.*;import com.itextpdf.text.pdf.*;public class HeaderFooter extends PdfPageEventHelper {String header;PdfTemplate total;public void setHeader(String header) {this.header = header;}public void onOpenDocument(PdfWriter writer, Document document) {total = writer.getDirectContent().createTemplate(30, 16);}public void onEndPage(PdfWriter writer, Document document) {PdfPTable table = new PdfPTable(3);try {table.setWidths(new int[]{24, 2, 24});table.setTotalWidth(527);table.setLockedWidth(true);table.getDefaultCell().setFixedHeight(20);//.getDefaultCell().setBorder(Rectangle.BOTTOM); //显示边框table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);table.getDefaultCell().disableBorderSide(15);table.addCell(header);table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);table.addCell(String.format(\"%d/\", writer.getPageNumber()));PdfPCell cell = new PdfPCell(Image.getInstance(total));//cell.setBorder(Rectangle.BOTTOM); //显示边框cell.disableBorderSide(15);//通过行高度设置显示的位置cell.setMinimumHeight(790);cell.setVerticalAlignment(Element.ALIGN_BOTTOM);table.addCell(cell);table.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());} catch (DocumentException de) {throw new ExceptionConverter(de);}}public void onCloseDocument(PdfWriter writer, Document document) {ColumnText.showTextAligned(total, Element.ALIGN_CENTER, new Phrase(String.valueOf(writer.getPageNumber())), 3, 2, 0);}} ");
            String msg = JSONObject.toJSONString(protocol);
            int length = msg.getBytes(StandardCharsets.UTF_8).length;
            int leg = (length + "").length();
            protocol.setLength(length + leg);
            ctx.writeAndFlush(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("发生异常 {}", cause);
    }

    /**
     * 服务器断开，重新连接
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("通道不活跃，启动重新连接");
        NettyClient.connect();
    }
}
